#include <algorithm>

#include "Scene.h"
#include "MyWindow.h"
//#include "KeyboardInterface.h"
#include "MouseInterface.h"
#include "Entity.h"

using std::list;

Scene::Scene(MyWindow* window)
: m_entities(list<Entity*>()), m_window(window), m_screenSize()
{
    m_keyboard = m_window->getKeyboard();
    m_mouse = m_window->getMouse();
    m_nextScene = this;
}

Scene::~Scene(void)
{
    //Free any allocated memory
    //for (list<Entity*>::iterator entity = m_entities.begin();
    //     entity != m_entities.end(); ++entity)
    //{
    //    delete (*entity);
    //    (*entity) = NULL;
    //}

    //Clear the entities
    m_entities.clear();
}

bool Scene::isButtonPressed(int button) const
{
    return m_mouse->isButtonPressed(button);
}

bool Scene::isButtonHold(int button) const
{
    return m_mouse->isButtonHold(button);
}

bool Scene::hasButtonBeenReleased(int button) const
{
    return m_mouse->hasButtonBeenReleased(button);
}

void Scene::getMousePos(int& x, int& y)
{
    m_mouse->getMousePos(x, y);
    y = static_cast<int> (m_screenSize.height) - y;
}

bool Scene::isKeyPressed(MyKeyCode code)
{
    return m_keyboard->isKeyPressed(code);
}

void Scene::registerEntity(Entity* entity)
{
    if (std::find(m_entities.begin(), m_entities.end(), entity) != m_entities.end())
    {
        return;
    }
    m_entities.push_back(entity);
}

void Scene::unregisterEntity(Entity* entity)
{
    if (entity == NULL) {
        return;
    }

    for(EntityIterator it = m_entities.begin(); it != m_entities.end(); ++it)
    {
        if (entity == (*it)) {
            m_entities.erase(it);
            break;
        }
    }
}

void Scene::clearDeadEntities()
{
    for (EntityIterator entity = m_entities.begin(); entity != m_entities.end();)
    {
        if (!(*entity)->canBeRemoved())
        {
            ++entity;
            continue;
        }
        delete (*entity);
        entity = m_entities.erase(entity);
    }
}
